import React from 'react';
import {
  Tabs, Button, notification, Icon,
} from 'antd';
import {
  readAllMessage, getUnreadMessage, getSentMessage, getReadMessage,
} from 'services/message';
import websocket from 'utils/websocket';
import { getToken, getUserId } from 'services/token';
import { defaultRejectHandler } from 'utils/http';
import List from './List';

const { TabPane } = Tabs;


export default class Message extends React.Component {
  constructor() {
    super();
    this.state = {
      tabBar: this.unreadOperations,
      unreadList: [],
      sentList: [],
      readList: [],
    };
  }

  getMessage = () => {
    getUnreadMessage().then((data) => data.unread).then((data) => {
      data.reverse();
      this.setState({ unreadList: data });
    }, defaultRejectHandler);
    getSentMessage().then(((data) => data.sent)).then((data) => {
      data.reverse();
      this.setState({ sentList: data });
    }, defaultRejectHandler);
    getReadMessage().then(((data) => data.read)).then((data) => {
      data.reverse();
      this.setState({ readList: data });
    }, defaultRejectHandler);
  };

  readAll = () => {
    const userId = getUserId(getToken());
    readAllMessage(userId).then(() => {
      this.getMessage();
    }, defaultRejectHandler);
  };

  unreadOperations = (
    <>
      <Button type="primary" onClick={this.readAll} style={{ marginRight: '10px' }}>一键已读</Button>
      <Button icon="reload" onClick={this.getMessage} />
    </>
  );

  otherOperations = (
    <Button icon="reload" onClick={this.getMessage} />
  );

  updateUnreadMessage = () => {
    notification.open({
      message: '有新消息',
      icon: <Icon type="exclamation-circle" style={{ color: '#108ee9' }} />,
      placement: 'topLeft',
    });
    getUnreadMessage().then((data) => {
      this.setState({ unreadList: data.unread });
    }, defaultRejectHandler);
  }

  componentDidMount() {
    this.getMessage();
    websocket(this.updateUnreadMessage);
  }

  render() {
    const {
      tabBar, unreadList, readList, sentList,
    } = this.state;
    return (
      <Tabs
        defaultActiveKey="0"
        onChange={(activeKey) => {
          if (activeKey === '0') { this.setState({ tabBar: this.unreadOperations }); } else this.setState({ tabBar: this.otherOperations });
        }}
        tabBarExtraContent={tabBar}
      >
        <TabPane tab="未读消息" key="0">
          <List type="unread" dataSource={unreadList} />

        </TabPane>
        <TabPane tab="已读消息" key="1">
          <List type="read" dataSource={readList} />

        </TabPane>
        <TabPane tab="已发送消息" key="2">
          <List type="send" dataSource={sentList} />

        </TabPane>
      </Tabs>
    );
  }
}
